package com.lzq.leetcode.hoot100;

import com.lzq.leetcode.hoot100.ds.ListNode;

public class s25 {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode tempHead = new ListNode();
        tempHead.next = head;
        ListNode pre = tempHead;
        ListNode tail = null;
        while ((tail = getK(pre, k)) != null) {
            ListNode newTail = pre.next;
            ListNode temp = tail.next;
            tail.next = null;
            reverse(pre.next);
            pre.next = tail;
            pre = newTail;
            pre.next = temp;
        }
        return tempHead.next;
    }

    public ListNode getK(ListNode head, int k) {
        for (int i=0; i<k; i++) {
            head = head.next;
            if (head == null) {
                return null;
            }
        }
        return head;
    }

    public void reverse(ListNode head) {
        ListNode tempHead = new ListNode();
        tempHead.next = head;
        ListNode pre = tempHead, cur = head;
        //pre.next = null;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
    }

    public static void main(String[] args) {
        s25 s25 = new s25();
        s25.reverseKGroup(new ListNode(new int[]{1,2,3,4,5}), 2);
    }
}
